package com.le.tester.book.effectivejava3rdchinese.secondReading.l79;

import com.le.tester.book.effectivejava3rdchinese.secondReading.l18.ForwardingSet;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * createTime：2024-11-14 10:49
 * description：当你不确定的时候，就不要同步类，减少同步才是重要的，不得已才去做同步
 * 不要在同步的代码调用不明的方法
 */
public class ObservableSet<E> extends ForwardingSet<E> {
    public ObservableSet(Set<E> s) {
        super(s);
    }

    private final List<SetObserver<E>> observers = new ArrayList<>();

    //java自提供，保证线程安全
    private final List<SetObserver<E>> observersCopy = new CopyOnWriteArrayList<>();

    public void addObserver(SetObserver<E> observer) {
        synchronized (observers) {
            observers.add(observer);
        }
    }

    public Boolean removeObserver(SetObserver<E> observer) {
        synchronized (observers) {
            return observers.remove(observer);
        }
    }

    private void notifyElementAdded(E element) {
        synchronized (observers) {
            for (SetObserver<E> observer : observers) {
                observer.added(this, element);
            }
        }
    }

    public boolean add(E element) {
        Boolean added = super.add(element);
        if (added) {
            notifyElementAdded(element);
        }
        return added;
    }

    public boolean addAll(Collection<? extends E> c) {
        boolean result = false;
        for (E element : c)
            result |= add(element);
        return result;
    }

    public static void main(String[] args) {
        ObservableSet<Integer> set = new ObservableSet<>(new HashSet<>());
        set.addObserver(new SetObserver<Integer>() {
            public void added(ObservableSet<Integer> s, Integer e) {
                System.out.println(e);
                if (e == 23)
                    s.removeObserver(this);
            }
        });
        for (int i = 0; i < 100; i++) {
            set.add(i);
        }
    }
}
